package no.knowit.eventorama.util;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import no.knowit.eventorama.dataobject.Event;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

public class MailUtil {

	public static void sendMail(String subject, String message,
			User owningUser, User attendingUser) {

		// get current logged in user
		User currentUser = UserServiceFactory.getUserService().getCurrentUser();
		Session session = Session.getDefaultInstance(new Properties(), null);

		try {
			Message msg = new MimeMessage(session);
			// from
			msg.setFrom(new InternetAddress(currentUser.getEmail(), currentUser
					.getNickname()));
			// to
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
					owningUser.getEmail(), owningUser.getNickname()));
			// subject
			msg.setSubject(subject);
			// message
			msg.setText(message);
			// SendIt
			Transport.send(msg);

		} catch (AddressException e) {
			throw new RuntimeException(e);
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static void sendMailAccept(User currentUser, Event event) {

		StringBuffer sbMessage = new StringBuffer("");
		sbMessage.append("Good news!");
		sbMessage.append("\n\nThe following user will attend your event \""
				+ event.getTitle() + "\": " + currentUser.getNickname() + " ("
				+ currentUser.getEmail() + ")");
		sbMessage.append("\n\nBest wishes, Eventorama team");
		MailUtil.sendMail("A user has accepted your event: "
				+ currentUser.getNickname(), sbMessage.toString(), event
				.getAuthor(), currentUser);
	}

}
